package com.qdxwx.manage.controller.company;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.channel.CompanyChannelService;
import com.qdxwx.data.service.company.CompanyAccountService;
import com.qdxwx.data.service.company.CompanyService;
import com.qdxwx.data.service.manager.ManagerService;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.channel.Channel;
import com.qdxwx.models.channel.CompanyChannel;
import com.qdxwx.models.company.Company;
import com.qdxwx.models.company.CompanyAccount;
import com.qdxwx.models.manager.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;

/**
 * 基本设置Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
//@Controller
//@RequestMapping("/company")
public class CompanyController extends BaseController {

    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyAccountService companyAccountService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private CompanyChannelService companyChannelService;


    // @GetMapping("/list.html")
    // @Permissions("company:edit")
    public String company() {
        return "company/company-list";
    }

    /**
     * 查询基本设置列表
     */
    // @PostMapping("/list.json")
    //@ResponseBody
    // @Permissions("company:edit")
    public TableDataInfo list(HttpServletRequest request) {
        String mobile = request.getParameter("linkMobile");
        Company company = new Company();
        company.setParentId(TKConvert.toInteger(request.getParameter("parentId")));
        company.setCompanyName(request.getParameter("companyName"));
        company.setSiteDomain(request.getParameter("siteDomain"));
        company.setLinkName(request.getParameter("linkName"));
        company.setLinkMobile(TKString.isMobile(mobile) ? mobile : null);
        List<Company> list = companyService.getList(company, PageRequest.form(request));
        long count = companyService.count(company);
        return new TableDataInfo(list, count);
    }

    /**
     * 新增修改基本设置
     */
    //@GetMapping("/edit/{companyId}")
    //@Permissions("company:edit")
    public String edit(@PathVariable("companyId") int companyId, ModelMap mmap) {
        Company company;
        if (companyId > 0) {
            company = companyService.get(companyId);
        } else {
            company = new Company();
        }
        mmap.put("company", company);
        return "company/company-edit";
    }

    /**
     * 修改保存基本设置
     */
    // @Log(title = "保存机构设置", businessType = BusinessType.UPDATE)
    // @PostMapping("/save.json")
    // @ResponseBody
    // @Permissions("company:edit")
    public AjaxResult save(HttpServletRequest request) {
        String companyName = TKString.queryKey(request.getParameter("companyName"));
        if (TKString.isEmpty(companyName)) return error("机构名称不能为空");
        String siteName = TKString.queryKey(request.getParameter("siteName"));
        if (TKString.isEmpty(siteName)) return error("网站名称不能为空");
        String siteDomain = request.getParameter("siteDomain");
        String description = request.getParameter("description");
        String keywords = request.getParameter("keywords");
        String copyright = request.getParameter("copyright");
        String contact = request.getParameter("contact");
        String linkName = request.getParameter("linkName");
        String linkMobile = request.getParameter("linkMobile");
        int companyId = TKConvert.toInteger(request.getParameter("companyId"));
        LocalDate expireDate = TKConvert.toLocalDate(request.getParameter("expireDate"), LocalDate.now().plusDays(15));
        if (LocalDate.now().isAfter(expireDate)) return error("过期时间必须大于现在时间");
        Company company;
        if (companyId > 0) {
            company = companyService.get(companyId);
            if (company == null) {
                return error("找不到指定修改的机构");
            }
            Manager manager = managerService.getByMobile(linkMobile);
            if(manager != null && !manager.getCompanyId().equals(company.getCompanyId())){
                return error("站长管理员已存在");
            }
        } else {
            company = new Company();
        }
        company.setParentId(TKConvert.toInteger(request.getParameter("parentId")));
        company.setCompanyName(companyName);
        company.setSiteName(siteName);
        company.setSiteDomain(siteDomain);
        company.setLogo(request.getParameter("logo"));
        company.setIco(request.getParameter("ico"));
        company.setQrcode(request.getParameter("qrcode"));
        company.setDescription(description);
        company.setKeywords(keywords);
        company.setCopyright(copyright);
        company.setContact(contact);
        company.setLinkName(linkName);
        company.setLinkMobile(linkMobile);
        company.setRemarks(request.getParameter("remarks"));
        company.setExpireDate(expireDate);
        company.setUpdateBy(SessionUtils.getManager().getManagerName());
        int row;
        if (companyId > 0) {
            row = companyService.update(company);
        } else {
            row = companyService.insert(company);
            if(row > 0){
                Manager manager = new Manager();
                manager.setCompanyId(company.getCompanyId());
                manager.setMobile(company.getLinkMobile());
                manager.setManagerName(company.getLinkName());
                manager.setLoginName(company.getLinkMobile());
                manager.setIsDisabled(0);
                manager.setCreateBy(SessionUtils.getLoginName());
                manager.setLoginPwd(TKConvert.toPWD(TKString.getRanString(8)));
                manager.setSex(2);
                manager.setRoleIds(TKConvert.toIntArray("3"));
                manager.setPostIds(TKConvert.toIntArray("4"));
                managerService.insert(manager);
                //默认设置开启所有频道
                Channel channel = new Channel();
                channel.setIsDisabled(0);
                channel.setIsHide(0);
                List<Channel> channelList = channelService.getList(channel, null);
                for (Channel channels:channelList) {
                    CompanyChannel companyChannel = new CompanyChannel();
                    companyChannel.setCompanyId(company.getCompanyId());
                    companyChannel.setChannelId(channels.getChannelId());
                    companyChannel.setSort(channels.getSort());
                    companyChannelService.insert(companyChannel);
                }
            }
        }
        return toAjax(row);
    }

    /**
     * 禁用或启用
     */
    // @PostMapping("/disabled.json")
    // @ResponseBody
    // @Permissions("company:edit")
    public AjaxResult disabled(HttpServletRequest request) {
        int companyId = TKConvert.toInteger(request.getParameter("companyId"));
        if (companyId < 1) return error("参数异常");
        int isDisabled = TKConvert.toInteger(request.getParameter("isDisabled"));
        Company company = new Company();
        company.setCompanyId(companyId);
        company.setIsDisabled(isDisabled >= 1 ? 1 : 0);
        int row = companyService.updateDisabled(company);
        if(row > 0){
            //同时禁用机构账户
            CompanyAccount account = new CompanyAccount();
            account.setCompanyId(companyId);
            account.setIsDisabled(isDisabled);
            companyAccountService.update(account);
        }
        return toAjax(row);
    }
}
